package com.shundr.shipper.truck;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shundr.shipper.R;
import com.shundr.shipper.base.BaseActivity;
import com.shundr.shipper.common.http.CommonRequest;
import com.shundr.shipper.common.util.CommonConfig;
import com.shundr.shipper.common.util.DialogUtil;
import com.shundr.shipper.common.util.LImageLoader;
import com.shundr.shipper.common.util.ProgressDialogHelper;
import com.shundr.shipper.common.util.ToastHelper;
import com.shundr.shipper.common.view.DialogDisplay.OnDisplayListener;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.frame.http.LHttpRequest;
import com.shundr.shipper.frame.util.StringUtil;
import com.shundr.shipper.order.CreateOrderActivity;
import com.shundr.shipper.truck.ContactTrucker.OnCallListener;
import com.shundr.shipper.truck.http.UserTruckRequest;
import com.shundr.shipper.truck.model.TruckInfo;
import com.shundr.shipper.user.LoginActivity;

/**
 * 车辆详情
 * TruckCommonDetailActivity
 * 
 * @author larry 2015-4-27 下午2:30:31 
 * @version 1.0.0
 *
 */
public class FamTruckDetailActivity extends BaseActivity implements OnClickListener{
	
	private LinearLayout mLayoutBottom;
	
	private ImageView ivFull;//车辆照片
	
	private TextView tvCarCode;
	private TextView tvCarType;
	private TextView tvCarLength;
	private TextView tvCarWeight;
	private TextView tvCurrentCity;
	private TextView tvDirection;
	private TextView tvTime;
	private TextView tvContactor;
	
	private TextView tvStatus;
	
	private ImageView ivValidation;
	
	private ImageLoader mImageLoader;
	
	private int mId;
	
	private TruckInfo mInfo;
	
	private int flag = 0;//0默认拥有所有权限,1、车辆2、收藏
	private boolean delete = true;//是否可移除
	
	private Handler mHandler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case UserTruckRequest.GET_TRUCK_INFO_SUCCESSED:
					mInfo=(TruckInfo)msg.obj;
					initData(mInfo);
					ProgressDialogHelper.dismiss();
					break;
				case UserTruckRequest.DELETE_FAM_TRUCK_SUCCESSED:
					ProgressDialogHelper.dismiss();
					ToastHelper.toastShort(mContext, msg.obj.toString());
					new Timer().schedule(new TimerTask() {
						
						@Override
						public void run() {
							setResult(888);
							finish();
						}
					}, 600);
					break;
				case UserTruckRequest.UPDATE_TRUCK_STATUS_SUCCESSED:
					ProgressDialogHelper.dismiss();
					ToastHelper.toastShort(mContext, msg.obj.toString());
					setResult(888);
					break;
				case UserTruckRequest.REQUEST_FAILED:
					ProgressDialogHelper.dismiss();
					ToastHelper.toastShort(mContext, msg.obj.toString());
					finish();
					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.handleMessage(msg);
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_truck_common_detail);
		flag = getIntent().getIntExtra("flag", 0);
		delete = getIntent().getBooleanExtra("delete", true);
		try {
			mId = getIntent().getIntExtra("id", -1);
			if(mId < 0){
				finish();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		initView();
		ProgressDialogHelper.show(mContext, "正在加载中...");
		new UserTruckRequest(mContext, mHandler).getTruckInfo(mId);
	}
	
	private void initView(){
		mLayoutBottom = (LinearLayout)findViewById(R.id.layout_bottom);
		tvCarCode=(TextView)findViewById(R.id.tv_car_code);
		tvCarType=(TextView)findViewById(R.id.tv_car_type);			
		tvCarLength=(TextView)findViewById(R.id.tv_car_length);
		tvCarWeight=(TextView)findViewById(R.id.tv_car_weight);
		tvCurrentCity=(TextView)findViewById(R.id.tv_current_city);
		tvDirection=(TextView)findViewById(R.id.tv_direction);
		tvTime = (TextView)findViewById(R.id.tv_time);
		tvContactor = (TextView)findViewById(R.id.tv_contactor);
		tvStatus = (TextView)findViewById(R.id.tv_status);
		ivValidation = (ImageView)findViewById(R.id.iv_validation);
		
		ivFull = (ImageView)findViewById(R.id.iv_car_full);

		ivFull.setOnClickListener(this);
		initBottom();
		this.mImageLoader = ImageLoader.getInstance();
	}
	
	private void initBottom() {
		if(flag == 1){
			findViewById(R.id.btn_add_fam).setVisibility(View.GONE);
			findViewById(R.id.line_1).setVisibility(View.GONE);
		}else if(flag == 2){
			findViewById(R.id.btn_favorite).setVisibility(View.GONE);
			findViewById(R.id.line_2).setVisibility(View.GONE);
		}
		final Button btnAdd = (Button)findViewById(R.id.btn_add_fam);
		btnAdd.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						if(!LContext.isLogin()){
							startActivity(new Intent(mContext, LoginActivity.class));
							return;
						}
						new UserTruckRequest(mContext, new Handler(){
							@Override
							public void handleMessage(Message msg) {
								switch (msg.what) {
								case UserTruckRequest.ADD_FAM_TRUCK_SUCCESSED:
									try {
										ToastHelper.toastShort(mContext,msg.obj.toString());
										btnAdd.setClickable(false);
										btnAdd.setText("已关注");
										btnAdd.setTextColor(getResources().getColor(R.color.tv_text));
									} catch (Exception e) {
										e.printStackTrace();
									}
									break;
								case LHttpRequest.REQUEST_FAILED:
									try {
										ToastHelper.toastShort(mContext,msg.obj.toString());
									} catch (Exception e) {
										e.printStackTrace();
									}
									break;
								default:
									break;
								}
								super.handleMessage(msg);
							}
						}).addFamTruck(mId);
					}
				});
		final Button btnFavorite = (Button)findViewById(R.id.btn_favorite);
		btnFavorite.setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						new CommonRequest(mContext, new Handler() {
							@Override
							public void handleMessage(Message msg) {
								switch (msg.what) {
								case CommonRequest.ADD_FAVORITE_SUCCEED:
									try {
										ToastHelper.toastShort(mContext,msg.obj.toString());
										btnFavorite.setClickable(false);
										btnFavorite.setText("已收藏");
										btnFavorite.setTextColor(getResources().getColor(R.color.tv_text));
									} catch (Exception e) {
										e.printStackTrace();
									}
									break;
								case LHttpRequest.REQUEST_FAILED:
									try {
										ToastHelper.toastShort(mContext,msg.obj.toString());
									} catch (Exception e) {
										e.printStackTrace();
									}
									break;
								default:
									break;
								}
								super.handleMessage(msg);
							}
						}).addFavorite(mId, CommonConfig.OPERATE_OBJECT_TRUCK);
					}
				});
		findViewById(R.id.btn_call).setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						if(LContext.isLogin()){
							new CommonRequest(mContext, new Handler()).saveOperateHistory(mId, CommonConfig.OPERATE_OBJECT_TRUCK, CommonConfig.OPERATE_CALL,"");
							if (LContext.getUserValidationStatus() != -1) {//认证完
								OnCallPhone(mInfo);
							}else{//未认证通过
								ContactTrucker trucker = new ContactTrucker(mContext);
								trucker.setCallListener(new OnCallListener() {
									
									@Override
									public void onCall() {
										OnCallPhone(mInfo);
									}
								});
							}
			        	}else{
			        		mContext.startActivity(new Intent(mContext, LoginActivity.class));
			        	}
					}
				});
	}
	
	private void OnCallPhone(TruckInfo info){
		if(!StringUtil.isNull(info.getTruckerPhone())){
			LContext.truckInfo = info;
			String mobileText = info.getTruckerPhone().replace("-", "");
			Intent intent = new Intent();// 创建一个意图对象，用来激发拨号的Activity
			intent.setAction("android.intent.action.CALL");
			intent.setData(Uri.parse("tel:" + mobileText));
			mContext.startActivity(intent);// 方法内部会自动添加类别,android.intent.category.DEFAULT
			LContext.isOrdered = true;
		}else{
			ToastHelper.toastShort(mContext, "该车主未提供联系电话");
		}
	}
	
	private void initData(TruckInfo info){
		if(info == null){
			return;
		}
		try {
			mImageLoader.displayImage(info.getTruckPic(), ivFull,LImageLoader.mOptions);
			tvCarCode.setText(info.getTruckPlateNumber());
			if(StringUtil.isNull(info.getTruckPlateNumber())){
				tvCarCode.setText("车牌号不详");
			}else{
				String plateNumber=info.getTruckPlateNumber();
//				if(LContext.getUserValidationStatus() != -1){
					tvCarCode.setText(plateNumber);
//				}else{
//					plateNumber=plateNumber.substring(0, plateNumber.length()-2)+"**";
//					tvCarCode.setText(plateNumber);
//				}
			}
			if(StringUtil.isNull(info.getTruckType())){
				tvCarType.setText("未知");
			}else{
				tvCarType.setText(info.getTruckType());
			}
			tvCarWeight.setText(info.getTruckCapacity() + " 吨");
			if(StringUtil.isEqual(info.getTruckLength(), "23")){
				tvCarLength.setText(info.getTruckLength() + " 米以上");
			}else{
				tvCarLength.setText(info.getTruckLength() + " 米");
			}
			if(StringUtil.isNull(info.getTruckCurrentCity())){
				tvCurrentCity.setText("未知");
			}else{
				tvCurrentCity.setText(info.getTruckCurrentCity());
			}
			
			String direct = "";
			if(!StringUtil.isNull(info.getTruckForwardCity1())){
				direct = direct + info.getTruckForwardCity1() + ",";
			}
			if(!StringUtil.isNull(info.getTruckForwardCity2())){
				direct = direct + info.getTruckForwardCity2() + ",";
			}
			if(!StringUtil.isNull(info.getTruckForwardCity3())){
				direct = direct + info.getTruckForwardCity3() + ",";
			}
			if(!StringUtil.isNull(info.getTruckForwardCity4())){
				direct = direct + info.getTruckForwardCity4() + ",";
			}
			if(!StringUtil.isNull(direct)){
				direct = direct.substring(0, direct.length() - 1);
				tvDirection.setText(direct);
			}else{
				tvDirection.setText("未知");
			}
			
			tvTime.setText(info.getTruckUpdateTime());
			
			if(StringUtil.isNull(info.getTruckerName())){
				tvContactor.setText("车主未知");
			}else{
				tvContactor.setText(info.getTruckerName());
			}
			
			if(info.getTruckStatus() == 3){
				tvStatus.setText(mContext.getResources().getString(R.string.truck_freeing));
				tvStatus.setTextColor(mContext.getResources().getColor(R.color.btn_green_light));
			}else if(info.getTruckStatus() == 4){
				tvStatus.setText(mContext.getResources().getString(R.string.truck_busying));
				tvStatus.setTextColor(mContext.getResources().getColor(R.color.btn_orange_light));
			}else{
				tvStatus.setText(mContext.getResources().getString(R.string.truck_delete));
				tvStatus.setTextColor(mContext.getResources().getColor(R.color.btn_gray_light));
			}
			
			if(info.getTruckValidationStatus() == 0){
				ivValidation.setVisibility(View.GONE);
			}else if(info.getTruckValidationStatus() == 1){
				ivValidation.setImageResource(R.drawable.iv_truck_validation_successed);
				ivValidation.setVisibility(View.VISIBLE);
			}else{
				ivValidation.setImageResource(R.drawable.iv_truck_validation_failed);
				ivValidation.setVisibility(View.GONE);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_car_full:
			try {
				if(!StringUtil.isNull(mInfo.getTruckPic())){
					ArrayList<String> list = new ArrayList<String>();
					if(!StringUtil.isNull(mInfo.getTruckPic())){
						list.add(mInfo.getTruckPic());
					}
					if(list.size() > 0){
						openImageReview(mContext, 0, list);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;

		default:
			break;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if(flag == 1){
			if(delete){
				getSupportMenuInflater().inflate(R.menu.menu_confirm, menu);
				menu.getItem(0).setTitle("移除");
			}
		}
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_confirm:
			DialogUtil.noticeAlertDialog(mContext, "移除", "确定移除这部车辆吗？",
					new OnDisplayListener() {

						@Override
						public void confirm() {
							ProgressDialogHelper.show(mContext, "正在移除中...");
							new UserTruckRequest(mContext, mHandler).deleteFamTruck(mId);
						}

						@Override
						public void cancel() {

						}
					});
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		if(LContext.getCallLong(this) > 0 && LContext.isOrdered){
			startActivity(new Intent(mContext, CreateOrderActivity.class));
		}
	}
	
	@Override
	public void onDestroy() {
//		releaseImageView(ivFull);
		super.onDestroy();
	}

}
